package se

import (
	"sort"

	"gitee.com/xuender/oils/logs"
	"gitee.com/xuender/oils/sets"
	"gitee.com/xuender/oils/slices"
	"gitee.com/xuender/oils/tags"
	"gitee.com/xuender/oils/u32"
	"github.com/syndtr/goleveldb/leveldb/util"
)

// Min 索引缩小.
func (p *Service) Min() {
	indexs := p.indexs(p.fs.fileWordPrefix)
	m := make(map[uint32]*IndexData, len(indexs))
	ids := make(slices.Uint32s, len(indexs))

	for i, id := range indexs {
		ids[i] = id.ID
		m[id.ID] = id
	}

	sort.Sort(ids)

	fids := sets.NewUint32s()

	for i, id := range indexs {
		if ids[i] != id.ID {
			logs.Debug(id.ID, id.Count, id.Name)
			fids.Add(id.ID)
		}
	}

	for _, id := range ids {
		if fids.Has(id) {
			p.fs.Delete(m[id].Name)
		}
	}

	for i := len(indexs) - 1; i >= 0; i-- {
		id := indexs[i]

		logs.Debug("indexs", i, id.Name)

		if fids.Has(id.ID) {
			p.Index(id.Name)
		}
	}

	logs.Debug(len(indexs))
}

// 生成索引数据.
func (p *Service) indexs(prefix [2]byte) Indexs {
	ret := Indexs{}

	iter := p.ls.DB.NewIterator(util.BytesPrefix(prefix[:]), nil)
	for iter.Next() {
		key := iter.Key()
		tag := tags.Tags(iter.Value())
		id := u32.Uint32(key[2:])
		_, fi := p.fs.fileByID(id)

		ret = append(ret, &IndexData{
			ID:    id,
			Count: tag.Count(),
			Name:  fi.Name,
		})
	}

	sort.Sort(ret)

	return ret
}
